package cn.admobiletop.adsuyi.adapter.gdt.loader;

import android.app.Activity;

import com.qq.e.ads.splash.SplashAD;

import cn.admobiletop.adsuyi.ad.ADSuyiSplashAd;
import cn.admobiletop.adsuyi.ad.adapter.ADSuyiAdapterLoader;
import cn.admobiletop.adsuyi.ad.adapter.ADSuyiAdapterParams;
import cn.admobiletop.adsuyi.ad.data.ADSuyiPlatformPosId;
import cn.admobiletop.adsuyi.ad.listener.ADSuyiSplashAdListener;
import cn.admobiletop.adsuyi.ad.widget.ADSuyiSplashAdContainer;
import cn.admobiletop.adsuyi.adapter.gdt.listener.SplashAdListener;
import cn.admobiletop.adsuyi.util.ADSuyiAdUtil;

/**
 * @author ciba
 * @description 开屏广告加载器
 *              需要实现ADSuyiAdapterLoader<ADSuyiSplashAd, ADSuyiSplashAdListener>
 * @date 2020/4/7
 */
public class SplashAdLoader implements ADSuyiAdapterLoader<ADSuyiSplashAd, ADSuyiSplashAdListener> {

    private SplashAdListener splashAdListener;

    /**
     * 加载开屏广告
     * @param splashAd
     * @param adapterParams
     * @param adListener
     */
    @Override
    public void loadAd(ADSuyiSplashAd splashAd, ADSuyiAdapterParams adapterParams, ADSuyiSplashAdListener adListener) {
        if (!ADSuyiAdUtil.isReleased(splashAd)
                && splashAd.getContainer() != null
                && adapterParams != null
                && adapterParams.getPlatform() != null
                && adapterParams.getPlatformPosId() != null
                && adListener != null) {
            ADSuyiPlatformPosId adSuyiPlatformPosId = adapterParams.getPlatformPosId();

            // 广告加载的Activity
            Activity activity = splashAd.getActivity();
            // 广告布局容器
            ADSuyiSplashAdContainer container = splashAd.getContainer();
            // 广告平台广告位ID
            String platformPosId = adSuyiPlatformPosId.getPlatformPosId();

            loadSplashAd(activity, container, platformPosId, adListener);
        }
    }

    /**
     * 加载广点通开屏广告
     * @param activity      广告展示的Activity
     * @param platformPosId 广告平台广告位ID
     * @param adListener    广告监听回调
     */
    private void loadSplashAd(Activity activity, ADSuyiSplashAdContainer container, String platformPosId, ADSuyiSplashAdListener adListener) {
        // 构造开屏监听类，实现广点通开屏广告回调接口
        splashAdListener = new SplashAdListener(platformPosId, adListener);

        // 以下是广点通加载广告逻辑
        // 构造广点通SplashAD对象，传入必要的参数
        SplashAD splashAD = new SplashAD(activity
                , platformPosId
                , splashAdListener);

        // 加载并展示广点通开屏广告
        splashAD.fetchAndShowIn(container);
    }

    @Override
    public void onResumed() {
        // 目前不做处理
    }

    @Override
    public void onPaused() {
        // 目前不做处理
    }

    /**
     * ADSuyi广告对象被释放会调用该方法
     */
    @Override
    public void release() {
        if (splashAdListener != null) {
            splashAdListener.release();
            splashAdListener = null;
        }
    }
}
